********************************************************************************
*                                                                              *
*                       CREATE WORKERS' JOB STATUS CHANGES                     *
*                                                                              *
********************************************************************************


use "H:\Robots and Workers\Data\Workers_PS_LFS_panel_full.dta", clear
keep if indweight == 1

sort rinpersoon year
g empl = 1-nonempl
replace empl = . if (jobtype_selfempl==1 | jobtype_retired==1 | jobtype_student==1 | jobtype_other==1 | jobtype_employee==.)
g unempl = 1-empl

g newhire = beid!=beid[_n-1] if rinpersoon==rinpersoon[_n-1]
g newhire_fromunempl = beid!=beid[_n-1] if rinpersoon==rinpersoon[_n-1] & unempl[_n-1]==1

g leaver = beid!=beid[_n+1] if rinpersoon==rinpersoon[_n+1]

g leaver_adj = beid!=beid[_n+1] & beid==beid[_n-1] & beid==beid[_n-2] & beid==beid[_n-3] if rinpersoon==rinpersoon[_n+1] & rinpersoon==rinpersoon[_n-1] & rinpersoon==rinpersoon[_n-2] & rinpersoon==rinpersoon[_n-3]  
g leaver_adj3 = beid!=beid[_n+3] & beid!=beid[_n+2] & beid!=beid[_n+1] & beid==beid[_n-1] & beid==beid[_n-2] if rinpersoon==rinpersoon[_n+3] & rinpersoon==rinpersoon[_n+2] & rinpersoon==rinpersoon[_n+1] & rinpersoon==rinpersoon[_n-1] & rinpersoon==rinpersoon[_n-2] & rinpersoon==rinpersoon[_n-3] 
 
g leaver_newfirm = beid!=beid[_n+1] if rinpersoon==rinpersoon[_n+1] & unempl[_n+1]==0
g leaver_unempl = beid!=beid[_n+1] if rinpersoon==rinpersoon[_n+1] & unempl[_n+1]==1

g newposition = (baanid!=baanid[_n-1])*(beid==beid[_n-1]) if rinpersoon==rinpersoon[_n-1] & year < 2011
replace newposition = (ikvid!=ikvid[_n-1])*(beid==beid[_n-1]) if rinpersoon==rinpersoon[_n-1] & year >= 2011
g newposition_nexty = (baanid!=baanid[_n+1])*(beid==beid[_n+1]) if rinpersoon==rinpersoon[_n-1] & year < 2010
replace newposition_nexty = (ikvid!=ikvid[_n+1])*(beid==beid[_n+1]) if rinpersoon==rinpersoon[_n-1] & year >= 2010

drop if year<2009 // Keep everything from 2009 onwards
sort rinpersoon year
g Δjc_withinfirm = baanid!=baanid[_n+1] if year < 2010 & beid==beid[_n+1] & rinpersoon==rinpersoon[_n+1]
replace Δjc_withinfirm = ikvid!=ikvid[_n+1] if year>2010 & beid==beid[_n+1] & rinpersoon==rinpersoon[_n+1]
g Δjc_betweenfirm = beid!=beid[_n+1] if rinpersoon==rinpersoon[_n+1] & nonempl[_n+1]==0 & nonempl[_n]==0


sort rinpersoon year
foreach var in Δjc_withinfirm Δjc_betweenfirm { 
	replace `var' = 0 if `var'==.
	replace `var' = `var'+`var'[_n-1] if rinpersoon==rinpersoon[_n-1]
	replace `var' = . if year == 2020
}

keep rinpersoon year newhire* leaver* newposition* Δ*
compress
duplicates drop rinpersoon year, force
save "H:\Robots and Workers\Data\Workers_PS_LFS_jobchanges.dta", replace

